package com.useeinfo.oa.open.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.logger.biz.FacilityLogBiz;
import com.useeinfo.oa.modules.logger.entity.FacilityLog;
import com.useeinfo.oa.modules.logger.enums.LogTypeEnum;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by 陈炜 on 2018/12/13.
 */
@RestController
@RequestMapping("/api/facility")
public class FacilityAPI {
    private final static Logger logger = LoggerFactory.getLogger(FacilityAPI.class);
    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private AreaBiz areaBiz;
    @Autowired
    private ResourceBiz resourceBiz;
    @Autowired
    private FacilityLogBiz facilityLogBiz;
    @Autowired
    private OrganizationBiz organizationBiz;

    /**
     * 设备列表
     */
    @RequestMapping(value = "/getFacilityList")
    public ResultDto getFacilityList(@RequestParam(value = "pageIndex", required = false) String pageIndexParam,
                                     @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                     @RequestParam(value = "rootCatId", required = false) String rootCatId,
                                     @RequestParam(value = "facilityCatId", required = false) String facilityCatId,
                                     @RequestParam(value = "areaId", required = false) String areaId,
                                     @RequestParam(value = "searchParam", required = false) String searchParam,
                                     HttpServletRequest request){
        QueryParam queryParam = new QueryParam(pageIndexParam, pageSizeParam);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        if(StringUtils.isNotBlank(searchParam)){
            queryParam.getSqlMap().put("searchParam", searchParam);
        }
        if(StringUtils.isNotBlank(facilityCatId)){
            queryParam.getSqlMap().put("facilityCatId", facilityCatId);
        }
        if(StringUtils.isNotBlank(areaId)){
            queryParam.getSqlMap().put("areaId", areaId);
        }
        if(StringUtils.isNotBlank(rootCatId)){
            queryParam.getSqlMap().put("facilityCatIds", facilityCatBiz.getChildrenCatIds(StringConverters.ToLong(rootCatId)));
        }

        List<Facility> facilityList =facilityBiz.findList(queryParam);
        Long count =facilityBiz.totalRecord(queryParam.getSqlMap());
//        List<Facility> facilityList2 =facilityBiz.findList(queryParam);
//        int total = 0;
//        if(CollectionUtils.isNotEmpty(facilityList2)){
//            total = facilityList2.size();
//        }
        JSONArray array = new JSONArray();
        for (Facility facility : facilityList){
            JSONObject json = new JSONObject();
            json.put("name",facility.getName());
            json.put("id",facility.getId());
            json.put("position", StringConverters.null2String(facility.getPosition()));
            json.put("latitude", StringConverters.null2String(facility.getLatitude()));
            json.put("longitude", StringConverters.null2String(facility.getLongitude()));
            json.put("areaName","");
            json.put("rootCatName","");
            json.put("facilityCatName","");
            json.put("qrCode", "");
            json.put("isAbnormal", facility.isAbnormal());
            json.put("isStop", facility.isStop());
            json.put("code",facility.getCode());
            FacilityCat facilityCat = facility.getFacilityCat();
            if(facilityCat!=null){
                FacilityCat rootCat = facilityCatBiz.findRootCat(facilityCat.getId());
                json.put("rootCatName",rootCat.getCatName());
                json.put("facilityCatName",facilityCat.getCatName());
            }
            if(facility.getArea()!=null){
                json.put("areaName",facility.getArea().getAreaName());
            }
            if(StringUtils.isNotBlank(facility.getCode())){
                json.put("qrCode", facility.getCode());
            }
            if(StringUtils.isNotBlank(facility.getQrCode())){
                json.put("qrCode", facility.getQrCode());
            }
            String fieldPhotoPath = "";
            if (facility.getFieldPhoto() != null && facility.getFieldPhoto().size() != 0) {
                List<Resource> resourceList = new ArrayList<Resource>(facility.getFieldPhoto());
                fieldPhotoPath = resourceList.get(0).getPath();
            }
            json.put("fieldPhotoPath", fieldPhotoPath);
            array.add(json);
        }
        JSONObject json = new JSONObject();
        json.put("total",count);
        json.put("rows",array);
        return ResultUtil.success(json);
    }

    /**
     * 根据设备ID查询关联设备列表
     */
    @RequestMapping(value = "/getRelationFacilityList")
    public ResultDto getRelationFacilityList(@RequestParam(value = "pageIndex", required = false) String pageIndexParam,
                                             @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                             @RequestParam(value = "facilityId", required = false) String facilityId,
                                             HttpServletRequest request){
        JSONArray array = new JSONArray();
        JSONObject json = new JSONObject();
        if(StringUtils.isBlank(facilityId)){
            json.put("total",0);
            json.put("rows",array);
            return ResultUtil.success(json);
        }
        Facility relationFacility = facilityBiz.findModel(StringConverters.ToLong(facilityId));
        if(relationFacility==null){
            json.put("total",0);
            json.put("rows",array);
            return ResultUtil.success(json);
        }
        QueryParam queryParam = new QueryParam(pageIndexParam, pageSizeParam);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        queryParam.getSqlMap().put("relationId", facilityId);
        if(relationFacility.getParentId()!=null){
            queryParam.getSqlMap().put("relationParentId", relationFacility.getParentId()+"");
        }
        List<Facility> facilityList =facilityBiz.findList(queryParam);
        queryParam.setPageNow(-1);
        queryParam.setPageSize(-1);
        List<Facility> facilityList2 =facilityBiz.findList(queryParam);
        int total = 0;
        if(CollectionUtils.isNotEmpty(facilityList2)){
            total = facilityList2.size();
        }
        for (Facility facility : facilityList){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",facility.getId());
            jsonObject.put("name",facility.getName());
            jsonObject.put("position", StringConverters.null2String(facility.getPosition()));
            jsonObject.put("latitude", StringConverters.null2String(facility.getLatitude()));
            jsonObject.put("longitude", StringConverters.null2String(facility.getLongitude()));
            jsonObject.put("areaName","");
            jsonObject.put("rootCatName","");
            jsonObject.put("facilityCatName","");
            jsonObject.put("qrCode", "");
            jsonObject.put("isAbnormal", facility.isAbnormal());
            jsonObject.put("isStop", facility.isStop());
            FacilityCat facilityCat = facility.getFacilityCat();
            if(facilityCat!=null){
                FacilityCat rootCat = facilityCatBiz.findRootCat(facilityCat.getId());
                jsonObject.put("rootCatName",rootCat.getCatName());
                jsonObject.put("facilityCatName",facilityCat.getCatName());
            }
            if(facility.getArea()!=null){
                jsonObject.put("areaName",facility.getArea().getAreaName());
            }
            if(StringUtils.isNotBlank(facility.getCode())){
                jsonObject.put("qrCode", facility.getCode());
            }
            if(StringUtils.isNotBlank(facility.getQrCode())){
                jsonObject.put("qrCode", facility.getQrCode());
            }
            String fieldPhotoPath = "";
            if (facility.getFieldPhoto() != null && facility.getFieldPhoto().size() != 0) {
                List<Resource> resourceList = new ArrayList<Resource>(facility.getFieldPhoto());
                fieldPhotoPath = resourceList.get(0).getPath();
            }
            jsonObject.put("fieldPhotoPath", fieldPhotoPath);
            array.add(jsonObject);
        }
        json.put("total",total);
        json.put("rows",array);
        return ResultUtil.success(json);
    }

    /**
     * 获取设备详情通过ID
     */
    @RequestMapping(value = "/getFacilityDetailById")
    public ResultDto getFacilityDetailById(@RequestParam(value = "id", required = false) String id,
                                       HttpServletRequest request){
        Facility facility =facilityBiz.findModel(StringConverters.ToLong(id));
        JSONObject json = new JSONObject();
        if(facility==null){
            return  ResultUtil.error("无此设备");
        }
        json = facility.toDetailJSONObject();
        //设备专业名称
        json.put("rootCatName","");
        json.put("rootCatId",null);
        if(facility.getFacilityCat()!=null){
            FacilityCat rootCat = facilityCatBiz.findRootCat(facility.getFacilityCat().getId());
            json.put("rootCatName",StringConverters.null2String(rootCat.getCatName()));
            json.put("rootCatId",StringConverters.null2Long(rootCat.getId()));
        }
        //主设备
        json.put("parentFacilityName","");
        if(facility.getParentId()!=null){
            Facility parentFacility =facilityBiz.findModel(facility.getParentId());
            if(parentFacility!=null){
                json.put("parentFacilityName",parentFacility.getName());
            }

        }
        //设备当前类型的上下级关系
        JSONArray catArray = new JSONArray();
        if(facility.getFacilityCat()!=null){
            String parentIds = facility.getFacilityCat().getParentIds();
            if(StringUtils.isNotBlank(parentIds)){
                String[] ids = parentIds.split(",");
                for (int i = 0; i < ids.length; i++) {
                    JSONObject jsonObject = new JSONObject();
                    FacilityCat facilityCat = facilityCatBiz.findModel(StringConverters.ToLong(ids[i]));
                    jsonObject.put("catId",facilityCat.getId());
                    jsonObject.put("catName",facilityCat.getCatName());
                    jsonObject.put("level",facilityCat.getLvl());
                    catArray.add(jsonObject);
                }
            }
            JSONObject object = new JSONObject();
            object.put("catId",facility.getFacilityCat().getId());
            object.put("catName",facility.getFacilityCat().getCatName());
            object.put("level",facility.getFacilityCat().getLvl());
            catArray.add(object);
        }
        json.put("catArray",catArray);
        //设备当前区域的上下级关系
        JSONArray areaArray = new JSONArray();
        if(facility.getArea()!=null){
            String parentIds = facility.getArea().getParentIds();
            if(StringUtils.isNotBlank(parentIds)){
                String[] ids = parentIds.split(",");
                for (int i = 0; i < ids.length; i++) {
                    JSONObject jsonObject = new JSONObject();
                    Area area = areaBiz.findModel(StringConverters.ToLong(ids[i]));
                    jsonObject.put("areaId",area.getId());
                    jsonObject.put("areaName",area.getAreaName());
                    jsonObject.put("level",area.getLvl());
                    areaArray.add(jsonObject);
                }
            }
            JSONObject object = new JSONObject();
            object.put("areaId",facility.getArea().getId());
            object.put("areaName",facility.getArea().getAreaName());
            object.put("level",facility.getArea().getLvl());
            areaArray.add(object);
        }
        json.put("areaArray",areaArray);


        return ResultUtil.success(json);
    }

    /**
     * 获取设备详情 通过code
     */
    @RequestMapping(value = "/getFacilityDetailByCode")
    public ResultDto getFacilityDetailByCode(@RequestParam(value = "code", required = false) String code,
                                             HttpServletRequest request){
        if(StringUtils.isBlank(code)){
            return ResultUtil.error("获取设备code失败");
        }
        QueryParam queryParam = new QueryParam();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业信息失败");
        }
        queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        queryParam.getSqlMap().put("code", code);
        List<Facility> facilityList = facilityBiz.findList(queryParam);
        if(CollectionUtils.isEmpty(facilityList)){
            return ResultUtil.error("无此设备");
        }
        Facility facility = facilityList.get(0);
        JSONObject json = new JSONObject();
        if(facility==null){
            return  ResultUtil.success(json);
        }
        json = facility.toDetailJSONObject();
        //设备专业名称
        json.put("rootCatName","");
        if(facility.getFacilityCat()!=null){
            FacilityCat rootCat = facilityCatBiz.findRootCat(facility.getFacilityCat().getId());
            json.put("rootCatName",StringConverters.null2String(rootCat.getCatName()));
        }
        //主设备
        json.put("parentFacilityName","");
        if(facility.getParentId()!=null){
            Facility parentFacility =facilityBiz.findModel(facility.getParentId());
            if(parentFacility!=null){
                json.put("parentFacilityName",parentFacility.getName());
            }

        }
        return ResultUtil.success(json);
    }

    /**
     * 获取设备详情 通过二维码
     */
    @RequestMapping(value = "/getFacilityDetailByQRCode")
    public ResultDto getFacilityDetailByQRCode(@RequestParam(value = "QRCode", required = false) String QRCode,
                                               HttpServletRequest request){
        if(StringUtils.isBlank(QRCode)){
            return ResultUtil.error("获取设备二维码失败");
        }
        QueryParam queryParam = new QueryParam();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业信息失败");
        }
        queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        queryParam.getSqlMap().put("qrCode", QRCode);
        List<Facility> facilityList = facilityBiz.findList(queryParam);
        if(CollectionUtils.isEmpty(facilityList)){
            return ResultUtil.error("无此设备");
        }
        Facility facility = facilityList.get(0);
        JSONObject json = new JSONObject();
        if(facility==null){
            return  ResultUtil.success(json);
        }
        json = facility.toDetailJSONObject();
        //设备专业名称
        json.put("rootCatName","");
        if(facility.getFacilityCat()!=null){
            FacilityCat rootCat = facilityCatBiz.findRootCat(facility.getFacilityCat().getId());
            json.put("rootCatName",StringConverters.null2String(rootCat.getCatName()));
        }
        //主设备
        json.put("parentFacilityName","");
        if(facility.getParentId()!=null){
            Facility parentFacility =facilityBiz.findModel(facility.getParentId());
            if(parentFacility!=null){
                json.put("parentFacilityName",parentFacility.getName());
            }

        }
        return ResultUtil.success(json);
    }

    /**
     * 获取设备类型列表
     */
    @RequestMapping(value = "/getFacilityCatList")
    public ResultDto getFacilityCatList(@RequestParam(value = "pageIndex", required = false) String pageIndexParam,
                                        @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                        @RequestParam(value = "ancestryId", required = false) String ancestryIdParam,
                                        @RequestParam(value = "parentId", required = false) String parentIdParam,
                                        HttpServletRequest request){
        QueryParam queryParam = new QueryParam(pageIndexParam, pageSizeParam);
        queryParam.setSqlOrder(" order by fc.lvl asc ");
        queryParam.getSqlMap().put("notBigParent", "随便写点什么");
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        if(StringUtils.isNotBlank(ancestryIdParam)){
            queryParam.getSqlMap().put("ancestryId", ancestryIdParam);
        }
        if(StringUtils.isNotBlank(parentIdParam)){
            queryParam.getSqlMap().put("parentId", parentIdParam);
        }
        List<FacilityCat> facilityCatList =facilityCatBiz.findList(queryParam);
        JSONArray array = new JSONArray();
        for (FacilityCat facilityCat : facilityCatList){
            JSONObject json = new JSONObject();
            json.put("facilityCatName",facilityCat.getCatName());
            json.put("id",facilityCat.getId());
            array.add(json);
        }
        return ResultUtil.success(array);
    }

    /**
     * 获取设备类型完全展示json
     */
    @RequestMapping(value = "/getFacilityCatTreeData")
    public ResultDto getFacilityCatTreeData(@RequestParam(value = "parentId", required = false) String parentIdParam,
                                            HttpServletRequest request){
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        JSONArray array = facilityCatBiz.findTreeData(StringConverters.ToLong(parentIdParam),enterprise!=null?enterprise.getId():null);
        return  ResultUtil.success(array);
    }

    /**
     * 获取设备专业列表
     */
    @RequestMapping(value = "/getRootFacilityCatList")
    public ResultDto getRootFacilityCatList(@RequestParam(value = "pageIndex", required = false) String pageIndexParam,
                                            @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                            HttpServletRequest request){
        QueryParam queryParam = new QueryParam(pageIndexParam, pageSizeParam);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        queryParam.getSqlMap().put("bigParent", "随便写什么");//只查根节点
        List<FacilityCat> facilityCatList =facilityCatBiz.findList(queryParam);
        JSONArray array = new JSONArray();
        for (FacilityCat facilityCat : facilityCatList){
            JSONObject json = new JSONObject();
            json.put("rootCatName",facilityCat.getCatName());
            json.put("id",facilityCat.getId());
            array.add(json);
        }
        return ResultUtil.success(array);
    }


    /**
     * 更新设备定位信息
     */
    @RequestMapping(value = "/updateGPS")
    public ResultDto updateGPS(@RequestParam(value = "id", required = false) String id,
                               @RequestParam(value = "longitude", required = false) String longitudeParam,
                               @RequestParam(value = "latitude", required = false) String latitudeParam,
                               HttpServletRequest request){

        Facility facility =facilityBiz.findModel(StringConverters.ToLong(id));
        if(facility==null){
            return ResultUtil.error("无此设备");
        }
        if(StringUtils.isNotBlank(longitudeParam)){
            Double longitude;
            try {
                longitude = Double.parseDouble(longitudeParam);
            }catch(Exception e){
                return ResultUtil.error("经度异常");
            }
            if(longitude>180D||longitude<-180D){
                return ResultUtil.error("经度异常");
            }
            facility.setLongitude(longitude);
        }
        if(StringUtils.isNotBlank(latitudeParam)){
            Double latitude;
            try {
                latitude = Double.parseDouble(latitudeParam);
            }catch(Exception e){
                return ResultUtil.error("纬度异常");
            }
            if(latitude>90D||latitude<-90D){
                return ResultUtil.error("纬度异常");
            }
            facility.setLatitude(latitude);
        }
        facilityBiz.addOrUpdate(facility);
        return  ResultUtil.success();
    }

    /**
     * 新增设备
     */
    @RequestMapping(value = "/add")
    public ResultDto add(@RequestParam(value = "name", required = false) String name,
                         @RequestParam(value = "code", required = false) String code,
                         @RequestParam(value = "serialNum", required = false) String serialNum,
                         @RequestParam(value = "factory", required = false) String factory,
                         @RequestParam(value = "facilityCatId", required = false) String facilityCatId,
                         @RequestParam(value = "areaId", required = false) String areaId,
                         @RequestParam(value = "power", required = false) String power,
                         @RequestParam(value = "mainParm", required = false) String mainParm,
                         @RequestParam(value = "purpose", required = false) String purpose,
                         @RequestParam(value = "upPower", required = false) String upPower,
                         @RequestParam(value = "sparePower", required = false) String sparePower,
                         @RequestParam(value = "releaseDate", required = false) String releaseDate,
                         @RequestParam(value = "enableDate", required = false) String enableDate,
                         @RequestParam(value = "guarantee", required = false) String guarantee,
                         @RequestParam(value = "gridPerson", required = false) String gridPerson,
                         @RequestParam(value = "organizationId", required = false) String organizationId,
                         @RequestParam(value = "position", required = false) String position,
                         @RequestParam(value = "type", required = false) String type,
                         @RequestParam(value = "id", required = false) String id,
                         HttpServletRequest request){
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        boolean index = false;
        if(enterprise==null||systemUser==null){
            return ResultUtil.error("参数异常");
        }
        if(StringUtils.isBlank(code)||StringUtils.isBlank(name)){
            return ResultUtil.error("设备编号和设备名称不得为空");
        }
        Facility facility;
        if(StringUtils.isBlank(id)){
            //新增
            facility = new Facility();
            facility.setCode(code);
            facility.setQrCode(code);
            index = true;
        }else{
            //更新
            facility = facilityBiz.findModel(StringConverters.ToLong(id));
        }
        if(facilityBiz.existFacility(facility,enterprise.getId())){
            return ResultUtil.error("设备编号已存在，请重新输入");
        }
        facility.setName(name);
        facility.setSerialNum(serialNum);
        facility.setFactory(factory);
        facility.setPosition(position);
        facility.setPower(power);
        facility.setMainParm(mainParm);
        facility.setPurpose(purpose);
        facility.setUpPower(upPower);
        facility.setSparePower(sparePower);
        facility.setGuarantee(guarantee);
        facility.setGridPerson(gridPerson);
        facility.setType(type);
        facility.setOrganization(organizationBiz.findModel(StringConverters.ToLong(organizationId)));
        if(StringUtils.isNotBlank(releaseDate)){
            facility.setReleaseDate(DateTimeUtils.parse("yyyy-MM-dd",releaseDate));
        }
        if(StringUtils.isNotBlank(enableDate)){
            facility.setEnableDate(DateTimeUtils.parse("yyyy-MM-dd",enableDate));
        }
        //设备类型(专业)
        FacilityCat facilityCat = facilityCatBiz.findModel(StringConverters.ToLong(facilityCatId));
        if(facilityCat!=null&&facility.getEnterprise()!=null&&enterprise.getId().equals(facility.getEnterprise().getId())){
            facility.setFacilityCat(facilityCat);
            facility.setRootCatId(facilityCatBiz.findRootCat(facilityCat.getId()).getId());
        }
        //区域
        Area area = areaBiz.findModel(StringConverters.ToLong(areaId));
        if(area!=null&&area.getEnterprise()!=null&&enterprise.getId().equals(area.getEnterprise().getId())){
            facility.setArea(area);
        }
        facility.setEnterprise(enterprise);
        facility.setSerialCode(facilityBiz.getSerialCode(enterprise.getId()+""));
        facilityBiz.addOrUpdate(facility);
        //添加设备日志
        FacilityLog facilityLog = new FacilityLog();
        if(index){
            facilityLog.setLogTypeEnum(LogTypeEnum.insert);
        }else{
            facilityLog.setLogTypeEnum(LogTypeEnum.update);
        }
        facilityLog.setUserName(systemUser.getUserName());
        facilityLog.setUserId(systemUser.getId());
        facilityLog.setFacilityId(facility.getId());
        facilityLogBiz.addOrUpdate(facilityLog);
        return  ResultUtil.success();
    }

    /**
     * 新增设备
     */
    @RequestMapping(value = "/update")
    public ResultDto update(@RequestParam(value = "id", required = false) String id,
                            @RequestParam(value = "serialNum", required = false) String serialNum,
                            @RequestParam(value = "factory", required = false) String factory,
                            @RequestParam(value = "power", required = false) String power,
                            @RequestParam(value = "mainParm", required = false) String mainParm,
                            @RequestParam(value = "purpose", required = false) String purpose,
                            @RequestParam(value = "upPower", required = false) String upPower,
                            @RequestParam(value = "sparePower", required = false) String sparePower,
                            @RequestParam(value = "releaseDate", required = false) String releaseDate,
                            @RequestParam(value = "enableDate", required = false) String enableDate,
                            @RequestParam(value = "guarantee", required = false) String guarantee,
                            @RequestParam(value = "gridPerson", required = false) String gridPerson,
                            @RequestParam(value = "organizationId", required = false) String organizationId,
                            HttpServletRequest request){
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        Facility facility = facilityBiz.findModel(StringConverters.ToLong(id));
        if(facility==null){
            return  ResultUtil.success();
        }
        facility.setSerialNum(serialNum);
        facility.setFactory(factory);
        facility.setPower(power);
        facility.setMainParm(mainParm);
        facility.setPurpose(purpose);
        facility.setUpPower(upPower);
        facility.setSparePower(sparePower);
        facility.setGuarantee(guarantee);
        facility.setGridPerson(gridPerson);
        facility.setOrganization(organizationBiz.findModel(StringConverters.ToLong(organizationId)));
        if(StringUtils.isNotBlank(releaseDate)){
            facility.setReleaseDate(DateTimeUtils.parse("yyyy-MM-dd",releaseDate));
        }else{
            facility.setReleaseDate(null);
        }
        if(StringUtils.isNotBlank(enableDate)){
            facility.setEnableDate(DateTimeUtils.parse("yyyy-MM-dd",enableDate));
        }else{
            facility.setEnableDate(null);
        }
        facilityBiz.addOrUpdate(facility);
        //添加设备日志
        FacilityLog facilityLog = new FacilityLog();
        facilityLog.setLogTypeEnum(LogTypeEnum.update);
        facilityLog.setUserName(systemUser.getUserName());
        facilityLog.setUserId(systemUser.getId());
        facilityLog.setFacilityId(facility.getId());
        facilityLogBiz.addOrUpdate(facilityLog);
        return  ResultUtil.success();
    }

    /**
     * 更新设备图片
     */
    @RequestMapping(value = "/updatePhoto")
    public ResultDto updatePhoto(@RequestParam(value = "id", required = false) String id,
                                 @RequestParam(value = "photoId", required = false) String photoId,
                                 @RequestParam(value = "type", required = false) String type,
                                 HttpServletRequest request){
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("企业获取异常");
        }
        Facility facility = facilityBiz.findModel(StringConverters.ToLong(id));
        if(facility==null){
            return ResultUtil.error("无此设备");
        }
        if(StringUtils.isBlank(type)){
            return ResultUtil.error("参数异常");
        }
        Resource resource = resourceBiz.findModel(StringConverters.ToLong(photoId));
        Set<Resource> resourceSet = new HashSet<>();
        if(resource!=null){
            resourceSet.add(resource);
        }

        if("fieldPhoto".equals(type)){
            if(resource!=null){
                facility.setFieldPhoto(resourceSet);
            }else{
                facility.setFieldPhoto(null);
            }
        }else if("platePhoto".equals(type)){
            if(resource!=null){
                facility.setPlatePhoto(resourceSet);
            }else{
                facility.setPlatePhoto(null);
            }
        }
        facilityBiz.addOrUpdate(facility);
        return  ResultUtil.success();
    }

    /**
     * 上传接口
     */
    @RequestMapping("/upload")
    public ResultDto upload(MultipartFile file, String type) {
        return facilityBiz.upload(file, type);
    }

    /**
     * 根据二维码值返回同组设备
     */
    @RequestMapping(value = "/getGroupList")
    public ResultDto getGroupList(@RequestParam(value = "QRCode", required = false) String QRCode, HttpServletRequest request){
        if(StringUtils.isBlank(QRCode)){
            return ResultUtil.error("获取设备二维码失败");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业信息失败");
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        queryParam.getSqlMap().put("qrCode", QRCode);
        List<Facility> facilityList = facilityBiz.findList(queryParam);
        if(CollectionUtils.isEmpty(facilityList)||facilityList.get(0)==null){
            return ResultUtil.error("无此设备");
        }
        Facility facility = facilityList.get(0);
        JSONObject data = new JSONObject();
        JSONArray rows = new JSONArray();
        if(facility.getFacilityGroup()==null){
            //只返回原设备
            JSONObject json = new JSONObject();
            json.put("id",facility.getId());
            json.put("name",facility.getName());
            json.put("code",facility.getCode());
            rows.add(json);
        }else{
            //获取同组设备
            QueryParam queryParam1 = new QueryParam();
            queryParam1.getSqlMap().put("enterpriseId", enterprise.getId()+"");
            queryParam1.getSqlMap().put("facilityGroupId", facility.getFacilityGroup().getId()+"");
            List<Facility> groupList = facilityBiz.findList(queryParam1);
            if(CollectionUtils.isNotEmpty(groupList)){
                for(Facility groupFacility:groupList){
                    JSONObject json = new JSONObject();
                    json.put("id",groupFacility.getId());
                    json.put("name",groupFacility.getName());
                    json.put("code",groupFacility.getCode());
                    rows.add(json);
                }
            }
        }
        data.put("rows",rows);
        return ResultUtil.success(data);
    }
}
